<template>
  <div class="file">
    <back style="z-index: 99" />
    <el-input
      style="width: 300px; margin-right: 12px"
      v-model="fileName"
      placeholder="请输入文件名"
      :suffix-icon="Search"
      size="large"
      clearable
    />
    <el-button plain @click="onDoSearch" size="large" type="primary">搜索</el-button>
    <el-table border :data="files" style="width: 100%;margin-top: 20px">
      <el-table-column align="center" label="文件名">
        <template #default="{ row }">
          <div @click="download(row.filepath)" class="c-p filename">
            {{ formatFileName(row.filename) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" width="150px" label="发布时间">
        <template #default="{ row }">
          <div>{{ row.createTime?.split(' ')[0] ?? '-' }}</div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      class="m-t-10 m-b-10"
      style="justify-content: flex-end"
      layout="prev, pager, next"
      small
      :total="total"
      :page-size="10"
      v-model:current-page="current"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ElTable, ElTableColumn } from 'element-plus';
import { useDownload } from '@/hooks/useDownload';
import { getFileList } from '@/api/file';
import back from '@/components/back/index.vue';
import { Search } from '@element-plus/icons-vue';

// 下载文件的方法，传个url即可
const { download } = useDownload();

interface File {
  filename: string;
  filepath: string;
  createTime: string;
}

// 查询某个文件
const fileName = ref('');
function onDoSearch() {
  localGetFileList();
}

const files = ref<File[]>([]);
const total = ref<number>(0);
onMounted(() => {
  localGetFileList();
});
function localGetFileList() {
  getFileList({
    current: current.value,
    size: 10,
    fileName: fileName.value ? fileName.value : null,
  }).then((res: any) => {
    if (res.code === 200) {
      files.value = res.data?.records;
      total.value = res.data?.total;
    }
  });
}
// 分页
const current = ref<number>(1);
function handleCurrentChange(val: number) {
  current.value = val;
  localGetFileList();
}
function formatFileName(filename: string) {
  const extension = filename.substring(filename.lastIndexOf('.') + 1);
  const originName = filename.substring(0, filename.lastIndexOf('_'));
  return `${originName}.${extension}`;
}
</script>

<style lang="scss" scoped>
.file {
  padding: 40px;
}

.file .filename:hover {
  text-decoration: none;
  color: #409eff;
}
</style>
